package dk.mirasola.systemtraining.bridgewidgets.client.ui.editor;


import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.ValueBoxBase;
import com.google.gwt.user.client.ui.Widget;

public abstract class IntervalEditor extends Composite {
    interface IntervalEditorUIBinder extends UiBinder<Widget, IntervalEditor> {
    }

    private static IntervalEditorUIBinder uiBinder = GWT.create(IntervalEditorUIBinder.class);

    private KeyUpHandler keyUpHandler = new KeyUpHandler() {
        private void invalid() {
            intervalMin.addStyleDependentName("invalid");
            intervalMax.addStyleDependentName("invalid");
        }

        @Override
        public void onKeyUp(KeyUpEvent event) {
            try {
                int min = Integer.parseInt(intervalMin.getText());
                int max = Integer.parseInt(intervalMax.getText());
                if (min < getIntervalMin() || min > getIntervalMax() || max < getIntervalMin() || max > getIntervalMax() || min > max) {
                    invalid();
                } else {
                    intervalMin.removeStyleDependentName("invalid");
                    intervalMax.removeStyleDependentName("invalid");
                    validMin = min;
                    validMax = max;
                }
            } catch (NumberFormatException e) {
                invalid();
            }
        }
    };


    private int validMin;
    private int validMax;

    @UiField
    TextBox intervalMin;
    @UiField
    TextBox intervalMax;
    @UiField(provided = true)
    HorizontalPanel panel;

    protected IntervalEditor() {
        panel = new HorizontalPanel();
        panel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);

        initWidget(uiBinder.createAndBindUi(this));

        intervalMin.setAlignment(ValueBoxBase.TextAlignment.RIGHT);
        intervalMin.addKeyUpHandler(keyUpHandler);
        intervalMax.setAlignment(ValueBoxBase.TextAlignment.RIGHT);
        intervalMax.addKeyUpHandler(keyUpHandler);
    }

    protected int getValidMin() {
        return validMin;
    }

    protected void setValidMin(int min) {
        intervalMin.setValue(String.valueOf(min));
        validMin = min;
    }

    protected int getValidMax() {
        return validMax;
    }

    protected void setValidMax(int max) {
        intervalMax.setValue(String.valueOf(max));
        validMax = max;
    }

    protected abstract int getIntervalMax();

    protected abstract int getIntervalMin();
}

